/*
 * $Id: ValidatorThread.java 94 2009-04-29 13:51:31Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.gui.deltagui.validation;

import java.util.Queue;

import deltadesk.gui.deltagui.graphics.GraphicsUtil;
import deltadesk.gui.deltagui.layout.Layout;
import deltadesk.gui.deltagui.widget.Composite;
import deltadesk.gui.deltagui.widget.Control;

/**
 * ValidatorThread.
 * 
 * @author Andreas Meyer
 * @version $Revision: 94 $
 */
class ValidatorThread extends Thread {
	
	/** The queue for invalidated controls. */
	private final Queue<Composite> queue;
	
	/** The running state of the thread. */
	private boolean running = true;


	/**
	 * Construct the thread.
	 * 
	 * @param queue
	 */
	ValidatorThread(final Queue<Composite> queue) {
		
		super("DeltaGUI-ComponentValidator");
		this.queue = queue;
	}

	/**
	 * @param running the running to set
	 */
	public void setRunning(final boolean running) {
		this.running = running;
	}

	/**
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		
		while(running) {

			final Composite c = queue.poll();
			if(c == null) {
				
				GraphicsUtil.sleep(10);
				continue;
			}
			validate(c);
		} // end while
	}

	/**
	 * Validate the composite and all its children.
	 * 
	 * @param c
	 */
	private void validate(final Composite c) {

		final Layout layout = c.getLayout();
		if (layout != null) {

			layout.layout(c);
		} // end if

		for (int i=0; i<c.getChildCount(); i++) {

			final Control child  = c.get(i);
			if(child instanceof Composite) {
				
				validate((Composite)child);
			}
		} // end for

	}

}
